package com.project.easy.common.framework.web.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.project.easy.common.db.mybatisplus.core.dto.BaseCommonBean;
import  com.project.easy.common.util.collection.CollectionUtil;
import  com.project.easy.common.util.exception.business.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/10/3 21:40
 * @description: 基础控制层
 */
public abstract class BaseController {
    /**
     * 基础控制 request
     */
    @Autowired
    private HttpServletRequest request;
    /**
     * 公共状态切换
     * @param ids ID
     * @param service 服务
     * @param  function 方法
     * @param statusFn 状态
     * @param <T>  数据类型
     * @return 返回 true 成功， false 失败
     */
    protected <T extends BaseCommonBean>  Boolean switchStatus(IService service, Function<T, Consumer<Boolean>> function, List<Long> ids, Function<T, Boolean> statusFn) {
        if (CollectionUtil.isNull(ids) || Objects.isNull(function) || Objects.isNull(statusFn)) {
            return Boolean.FALSE;
        }
        List<T> dataList = service.listByIds(ids);

        if (CollectionUtil.isNull(dataList) || dataList.size() != ids.size()) {
            return Boolean.FALSE;
        }
        Map<Boolean, List<T>> booleanListMap = CollectionUtil.groupList(dataList, statusFn);

        if (booleanListMap.size() > 1) {
            throw  new BusinessException("批量状态操作只能是相同状态才能操作!");
        }
        for (T t : dataList) {
            function.apply(t).accept(!statusFn.apply(t));
        }
        return  service.updateBatchById(dataList);
    }
    /**
     * 公共删除单表
     * @param ids ID
     * @param service 服务
     * @param  function 方法
     * @param <T>  数据类型
     * @return 返回 true 成功， false 失败
     */
    protected <T extends BaseCommonBean>  Boolean del(IService service, Function<T, Consumer<Boolean>> function, List<Long> ids) {
        if (CollectionUtil.isNull(ids) || Objects.isNull(function)) {
            return Boolean.FALSE;
        }
        List<T> dataList = service.listByIds(ids);

        if (CollectionUtil.isNull(dataList) || dataList.size() != ids.size()) {
            return Boolean.FALSE;
        }
        for (T t : dataList) {
            function.apply(t).accept(Boolean.TRUE);
        }
        return  service.updateBatchById(dataList);
    }

}
